package com.hg.service.impl;


import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hg.common.HttpStatus;
import com.hg.exception.ServiceException;
import com.hg.mapper.HgMallDishMapper;
import com.hg.mapper.HgMallOrderChilderMapper;
import com.hg.mapper.HgMallOrderMapper;
import com.hg.mapper.HgMallShopMapper;
import com.hg.pojo.HgMallDish;
import com.hg.pojo.HgMallOrderChilder;
import com.hg.pojo.HgMallOrders;
import com.hg.pojo.HgMallShop;
import com.hg.pojo.dto.AddOrderDishVo;
import com.hg.pojo.dto.AddOrdersVo;
import com.hg.pojo.dto.SelectOrderDishVo;
import com.hg.service.HgMallOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class HgMallOrderServiceImpl extends ServiceImpl<HgMallOrderMapper, HgMallOrders> implements HgMallOrderService {

        @Autowired
        private HgMallOrderMapper hgMallOrderMapper;

        @Autowired
        private HgMallOrderChilderMapper hgMallOrderChilderMapper;


        @Autowired
        private HgMallDishMapper hgMallDishMapper;

        @Autowired
        private HgMallShopMapper hgMallShopMapper;


    /**
     * 查询订单信息
     *  分页和模糊查询
     * @param currentPage 当前页面
     * @param pageSize    页面大小
     * @param appid       appid
     * @param orderNum    订单num
     * @param oddNum      奇怪num
     * @param orderStatus 订单状态
     * @return {@link Page}<{@link HgMallOrders}>
     */
    @Override
    @Transactional
    public Page<HgMallOrders> selectHgMallOrdersList(int currentPage, int pageSize,String appid,String orderNum,String oddNum,Integer orderStatus) {
        Page<HgMallOrders> listPage =new Page<>(currentPage,pageSize);
        /*
        1、查询大订单，如果hgMallOrders是空，就查所有大订单
         */
        LambdaQueryWrapper<HgMallOrders> lm = getlmHgMallOrders();
        lm.orderByDesc(HgMallOrders::getCreateTime);
        lm.like(appid!=null,HgMallOrders::getAppid,appid);
        lm.like(orderNum!=null,HgMallOrders::getOrderNum,orderNum);
        lm.like(oddNum!=null,HgMallOrders::getOddNum,oddNum);
        lm.like(orderStatus!=null,HgMallOrders::getStatus,orderStatus);
        hgMallOrderMapper.selectPage(listPage, lm);
        List<HgMallOrders> hgMallOrders =listPage.getRecords();
         /*
        2、查每个订单的订单详情
         */
        for (HgMallOrders orders : hgMallOrders) {
            String orderId = orders.getId();
            //在订单子表中通过order_id查询出菜品id列表
            List<Integer> dishIdList = getdishIdByOrderId(orderId);
            //定义订单中的菜品列表
            List<SelectOrderDishVo> dishList = new ArrayList<>();
            //一个订单的总价格
            BigDecimal orderPriceAll = BigDecimal.ZERO;
            int shopId = 0;
            String shopName = "";
            for (Integer dishId : dishIdList) {

                //当前订单id每个菜品要了多少份
                LambdaQueryWrapper<HgMallOrderChilder> lmOrderChiler = getlmHgMallOrdersChilder();
                lmOrderChiler.eq(HgMallOrderChilder::getDishId,dishId).eq(HgMallOrderChilder::getOrdersId,orderId);
                HgMallOrderChilder orderChilder = hgMallOrderChilderMapper.selectOne(lmOrderChiler);
                //根据dish_id查询出这个订单的菜品信息
                LambdaQueryWrapper<HgMallDish> lmDish = getlmHgMallDish();
                lmDish.eq(HgMallDish::getId,dishId);
                HgMallDish dish = hgMallDishMapper.selectOne(lmDish);
                /*
                需要改进 //调郑子俊的接口SelectOrderDishVo dish = ***;
                 */
                SelectOrderDishVo orderDishVo = new SelectOrderDishVo();
                orderDishVo.setId(dishId);
                orderDishVo.setDishName(dish.getName());
                orderDishVo.setDishCount(orderChilder.getDishCount());
                orderDishVo.setIntroduce(orderChilder.getDishRequire());
                orderDishVo.setType(dish.getType());
                shopId = dish.getShopId();
                LambdaQueryWrapper<HgMallShop> lmShop=new LambdaQueryWrapper<>();
                lmShop.select(HgMallShop::getName);
                lmShop.eq(HgMallShop::getId,shopId);
                shopName = hgMallShopMapper.selectOne(lmShop).getName();
                //菜品总价
                BigDecimal dishPriceAll = dish.getPrice().multiply(new BigDecimal(orderChilder.getDishCount()));
                //在订单总价上累加菜品总价得到的结果就是订单总价
                orderPriceAll = orderPriceAll.add(dishPriceAll);
                //一个订单中有多个菜品
                dishList.add(orderDishVo);
            }
            //向订单中加入订单总价格
            orders.setPriceAll(orderPriceAll);
            orders.setShopId(shopId);
            orders.setShopName(shopName);
            //向订单中加入菜品
            orders.setOrderDishVo(dishList);
        }
        listPage.setRecords(hgMallOrders);

        return listPage;
    }


    /**
     *
     *
     * @param orderId 订单id
     * @return {@link HgMallOrders}
     *//*
    * 通过id查询
    * */
    @Override
    @Transactional
    public HgMallOrders selectHgMallOrdersForm(String orderId) {

        List<Integer> dishIdList = getdishIdByOrderId(orderId);
        if(dishIdList.isEmpty()){
            return null;
        }
        //定义订单中的菜品列表
        List<SelectOrderDishVo> dishList = new ArrayList<>();
        int shopId = 0;
        String shopName = "";
        for (Integer dishId : dishIdList) {
            //当前订单id每个菜品要了多少份
            LambdaQueryWrapper<HgMallOrderChilder> lmOrderChiler = getlmHgMallOrdersChilder();
            lmOrderChiler.eq(HgMallOrderChilder::getDishId,dishId).eq(HgMallOrderChilder::getOrdersId,orderId);
            HgMallOrderChilder orderChilder = hgMallOrderChilderMapper.selectOne(lmOrderChiler);
            //根据dish_id查询出这个订单的菜品信息
            LambdaQueryWrapper<HgMallDish> lmDish = getlmHgMallDish();
            lmDish.eq(HgMallDish::getId,dishId);
            HgMallDish dish = hgMallDishMapper.selectOne(lmDish);
            SelectOrderDishVo orderDishVo = new SelectOrderDishVo();
            orderDishVo.setId(dishId);
            orderDishVo.setDishName(dish.getName());
            orderDishVo.setDishCount(orderChilder.getDishCount());
            orderDishVo.setIntroduce(orderChilder.getDishRequire());
            orderDishVo.setType(dish.getType());
            shopId = dish.getShopId();
            LambdaQueryWrapper<HgMallShop> lmShop=new LambdaQueryWrapper<>();
            lmShop.select(HgMallShop::getName);
            lmShop.eq(HgMallShop::getId,shopId);
            shopName = hgMallShopMapper.selectOne(lmShop).getName();
            //一个订单中有多个菜品
            dishList.add(orderDishVo);
        }
        LambdaQueryWrapper<HgMallOrders> lm = getlmHgMallOrders();
        lm.eq(HgMallOrders::getId,orderId);
        HgMallOrders orders = hgMallOrderMapper.selectOne(lm);
        //向订单中加入菜品
        orders.setOrderDishVo(dishList);
        orders.setShopId(shopId);
        orders.setShopName(shopName);
        //7、返回
        return orders;
    }

    /**
     * 伪删除由订单信息
     *
     * @param ids id
     * @return int
     */
    @Override
    public int deleteByIds(String[] ids) {
        if (ids.length==0){
            return 0;

        }
        LambdaUpdateWrapper<HgMallOrders> lm =new LambdaUpdateWrapper<>();
        lm.set(HgMallOrders::getDelFlag,1);
        lm.in(HgMallOrders::getId,ids);
        int update = hgMallOrderMapper.update(null, lm);
        if (update>0){
            //更新子订单
                LambdaUpdateWrapper<HgMallOrderChilder> lmChilder=new LambdaUpdateWrapper<>();
                lmChilder.set(HgMallOrderChilder::getDelFlag,1);
                lmChilder.in(HgMallOrderChilder::getOrdersId,ids);
                hgMallOrderChilderMapper.update(null,lmChilder);
                return update;
        }
        return 0;
    }

    /**
     * 更新订单
     *
     * @param hgMallOrders hg商城订单
     * @return int
     */
    @Override
    @Transactional
    public int updateOrder(HgMallOrders hgMallOrders) {
            if (hgMallOrders==null){
                return 0;
            }
        //根据主表订单id，在订单子表中更新订单菜品
        //更新订单子表dishid
        //更新订单子表count
        //更新菜品销量，先得到原来的订单的菜品数量，减去原来的菜品数量，加上当前菜品数量
        //更新订单子表中客户的要求
        //总结我需要原来的订单的菜品数量，dishCount，introduce
        int i = 0;
            //获取
        List<SelectOrderDishVo> orderDishVo = hgMallOrders.getOrderDishVo();
        for (SelectOrderDishVo orderChilder : orderDishVo) {
            HgMallOrderChilder hgMallOrderChilder = new HgMallOrderChilder();
            hgMallOrderChilder.setOrdersId(hgMallOrders.getId());
            hgMallOrderChilder.setDishId(orderChilder.getId());
            LambdaQueryWrapper<HgMallOrderChilder> lmChilder = getlmHgMallOrdersChilder();
            if (hgMallOrderChilder.getOrdersId()!=null&&hgMallOrderChilder.getDishId()==null){
                            lmChilder.eq(HgMallOrderChilder::getOrdersId,hgMallOrderChilder.getOrdersId()).eq(HgMallOrderChilder::getDelFlag,0);
            }else if(hgMallOrderChilder.getOrdersId()==null&&hgMallOrderChilder.getDishId()!=null){
                lmChilder.eq(HgMallOrderChilder::getDishId,hgMallOrderChilder.getDishId()).eq(HgMallOrderChilder::getDelFlag,0);
            }else {
                lmChilder.eq(HgMallOrderChilder::getDishId,hgMallOrderChilder.getDishId()).eq(HgMallOrderChilder::getOrdersId,hgMallOrderChilder.getOrdersId()).eq(HgMallOrderChilder::getDelFlag,0);
            }
            List<HgMallOrderChilder> hgMallOrderChilders = hgMallOrderChilderMapper.selectList(lmChilder);
            for (HgMallOrderChilder mallOrderChilder : hgMallOrderChilders) {
                hgMallOrderChilder.setId(mallOrderChilder.getId());
            }
            hgMallOrderChilder.setDishCount(orderChilder.getDishCount());
            hgMallOrderChilder.setDishRequire(orderChilder.getIntroduce());
            LambdaUpdateWrapper<HgMallOrderChilder> lmUpdate=new LambdaUpdateWrapper<>();
            lmUpdate.set(hgMallOrderChilder.getOrdersId()!=null,HgMallOrderChilder::getOrdersId,hgMallOrderChilder.getOrdersId());
            lmUpdate.set(hgMallOrderChilder.getDishId()!=null,HgMallOrderChilder::getDishId,hgMallOrderChilder.getDishId());
            lmUpdate.set(hgMallOrderChilder.getDishRequire()!=null,HgMallOrderChilder::getDishRequire,hgMallOrderChilder.getDishRequire());
            lmUpdate.set(hgMallOrderChilder.getDishCount()!=null,HgMallOrderChilder::getDishCount,hgMallOrderChilder.getDishCount());
            lmUpdate.eq(HgMallOrderChilder::getId,hgMallOrderChilder.getId());
            hgMallOrderChilderMapper.update(hgMallOrderChilder,lmUpdate);
        }
        return i;
    }

    /**
     * 添加订单
     *
     * @param ordersVo 订单签证官
     * @return int
     */
    @Override
    @Transactional
    public int addOrder(AddOrdersVo ordersVo) {
        //用户id
        String appid = ordersVo.getAppid();
        //商铺id
        Integer shopId = ordersVo.getShopId();
        //订单详情
        List<AddOrderDishVo> orderDishVo = ordersVo.getOrderDishVo();
        /*
         * 1、添加主订单
         */
        HgMallOrders hgMallOrders = new HgMallOrders();
        //设置用户id
        hgMallOrders.setAppid(appid);
        //设置shopid
        hgMallOrders.setShopId(shopId);
        //设置取餐状态
        hgMallOrders.setMealStatus(0);
        //设置订单状态，status:0代表菜品未交付用户，1表示菜品已交付用户
        hgMallOrders.setStatus(0);
        //设置订单号
        String uuid = UUID.fastUUID().toString().replaceAll("-", "").substring(0, 12);
        hgMallOrders.setOddNum(uuid);
        hgMallOrders.setCreateBy(appid);

        //查询未处理的上一个订单的取单号,按店铺id、订单status查询,根据时间降序取第一个
        LambdaQueryWrapper<HgMallOrders> lmOrderNumByShop=new LambdaQueryWrapper<>();
        lmOrderNumByShop.select(HgMallOrders::getOrderNum);
        lmOrderNumByShop.eq(HgMallOrders::getShopId,shopId);
        lmOrderNumByShop.eq(HgMallOrders::getStatus,0);
        lmOrderNumByShop.orderByDesc(HgMallOrders::getCreateTime).last("limit 1");


        String newOrderNum = hgMallOrderMapper.selectOne(lmOrderNumByShop).getOrderNum();
        //定义取单号变量
        String orderNum;
        //如果没有新的订单则把当前订单设置为A-1
        if (newOrderNum != null) {
            //以“ - ”分割   //A-1
            String[] passNum = newOrderNum.split("-");
            //上一个未处理订单的取单号的字母转换为数字
            int headNum = passNum[0].charAt(0);//A
            //上一个未处理订单的取单号的数字序号
            int oldNum = Integer.parseInt(passNum[1]);//1
            //新增订单取单号的数字序号
            int newNum = oldNum + 1;//2
            //如果新的订单号数字序号超出100，让新的订单号的字母换下一位（A~Z）
            if (newNum >= 100 && headNum <= 90) {
                newNum = 1;
                headNum += 1;
            }
            //orderNum = headNum + "-" + newNum;
            orderNum = Character.toString((char) headNum) + '-' + newNum;
        } else {
            orderNum = "A-1";
        }
        hgMallOrders.setOrderNum(orderNum);
        //设置删除标志 0代表未删除，1代表已删除
        hgMallOrders.setDelFlag(String.valueOf(0));
        //设置订单创建时间
//        hgMallOrders.setCreateTime();
        //订单id
        hgMallOrders.setId(UUID.randomUUID().toString());
        //添加主订单
        int i = hgMallOrderMapper.insert(hgMallOrders);
        if(i==0){
            return 0;
        }
        //查询出这个店铺下新增的这个orderid ,按照创建日期降序查询和用户appid以及shopId,取第一个
        LambdaQueryWrapper<HgMallOrders> lmNew =new LambdaQueryWrapper<>();
        lmNew.select(HgMallOrders::getId);
        lmNew.eq(HgMallOrders::getAppid,hgMallOrders.getAppid());
        lmNew.eq(HgMallOrders::getShopId,hgMallOrders.getShopId());
        lmNew.eq(HgMallOrders::getDelFlag,0);
        lmNew.orderByDesc(HgMallOrders::getCreateTime).last("limit 1");
        String newOrederId = hgMallOrderMapper.selectOne(lmNew).getId();

        /*
         * 2、更新菜品的销量
         */
        //dishVo为单个菜品
        for (AddOrderDishVo dishVo : orderDishVo) {
            Integer dishId = dishVo.getDishId();
            //菜品数量
            Integer count = dishVo.getDishCount();
            //客户要求
            String requirement = dishVo.getIntroduce();
            //更新销量
            LambdaQueryWrapper<HgMallDish> lmQuery=new LambdaQueryWrapper<>();
            lmQuery.select(HgMallDish::getSales);
            lmQuery.eq(HgMallDish::getId,dishId);
            Integer oldsales = hgMallDishMapper.selectOne(lmQuery).getSales();
            LambdaUpdateWrapper<HgMallDish> lmUpdate=new LambdaUpdateWrapper<>();
            lmUpdate.set(HgMallDish::getSales,oldsales+count);
            lmUpdate.eq(HgMallDish::getId,dishId);
            int i1 = hgMallDishMapper.update(null,lmUpdate);
            if(i1==0){
                return 0;
            }
            /*
             * 3、添加子订单
             */
            HgMallOrderChilder OrderChilder = new HgMallOrderChilder();
            OrderChilder.setId(UUID.randomUUID().toString());
            OrderChilder.setOrdersId(newOrederId);
            OrderChilder.setDishId(dishId);
            OrderChilder.setCreateBy(appid);
            OrderChilder.setDelFlag(String.valueOf(0));
            OrderChilder.setDishCount(count);
            OrderChilder.setDishRequire(requirement);
            int row = hgMallOrderChilderMapper.insert(OrderChilder);
            if(row==0){
                return 0;
            }
        }
        return 1;
    }

    /**
     * 更新状态
     *
     * @param id     id
     * @param status 状态
     * @return int
     */
    @Override
    public int updateStatus(String id, int status) {
        LambdaUpdateWrapper<HgMallOrders> lm =new LambdaUpdateWrapper<>();

        if (id!=null){
            lm.set(HgMallOrders::getStatus,status);
            lm.eq(HgMallOrders::getId,id);
        }
        int update = hgMallOrderMapper.update(null, lm);
        if (update>0){
            return 1;
        }
        return 0;

    }

    /**
     * 更新是否取餐状态
     *
     * @param id         id
     * @param mealStatus 餐地位
     * @return int
     */
    @Override
    public int updateMealStatus(String id, int mealStatus) {
        /**
         * 先查询是否以消费 如果已经消费就不能取消取餐状态
         */
        LambdaQueryWrapper<HgMallOrders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(HgMallOrders::getStatus);
        queryWrapper.eq(HgMallOrders::getId,id);
        HgMallOrders mallOrders = this.getOne(queryWrapper);
        Integer status = mallOrders.getStatus();
        if (status == 1){
            //抛出异常 //已经消费 不能取消
            throw new ServiceException(HttpStatus.CODE_ERROR,"订单已消费，不能取消");
        }
        LambdaUpdateWrapper<HgMallOrders> lm =new LambdaUpdateWrapper<>();
        if (id!=null){
            lm.set(HgMallOrders::getMealStatus,mealStatus);
            lm.eq(HgMallOrders::getId,id);
        }
        int updateMealStatus = hgMallOrderMapper.update(null, lm);
        if (updateMealStatus>0){
            return 1;
        }
        return 0;
    }

    @Override
    public List<HgMallOrders> selectHgMAllOrdersAll() {
        LambdaQueryWrapper<HgMallOrders> lm = getlmHgMallOrders();
        List<HgMallOrders> hgMallOrders = hgMallOrderMapper.selectList(lm);
        for (HgMallOrders orders : hgMallOrders) {
            String orderId = orders.getId();
            //在订单子表中通过order_id查询出菜品id列表
            List<Integer> dishIdList = getdishIdByOrderId(orderId);
            //定义订单中的菜品列表
            List<SelectOrderDishVo> dishList = new ArrayList<>();
            //一个订单的总价格
            BigDecimal orderPriceAll = BigDecimal.ZERO;
            int shopId = 0;
            String shopName = "";
            for (Integer dishId : dishIdList) {

                //当前订单id每个菜品要了多少份
                LambdaQueryWrapper<HgMallOrderChilder> lmOrderChiler = getlmHgMallOrdersChilder();
                lmOrderChiler.eq(HgMallOrderChilder::getDishId,dishId).eq(HgMallOrderChilder::getOrdersId,orderId);
                HgMallOrderChilder orderChilder = hgMallOrderChilderMapper.selectOne(lmOrderChiler);
                //根据dish_id查询出这个订单的菜品信息
                LambdaQueryWrapper<HgMallDish> lmDish = getlmHgMallDish();
                lmDish.eq(HgMallDish::getId,dishId);
                HgMallDish dish = hgMallDishMapper.selectOne(lmDish);
                /*
                需要改进 //调郑子俊的接口SelectOrderDishVo dish = ***;
                 */
                SelectOrderDishVo orderDishVo = new SelectOrderDishVo();
                orderDishVo.setId(dishId);
                orderDishVo.setDishName(dish.getName());
                orderDishVo.setDishCount(orderChilder.getDishCount());
                orderDishVo.setIntroduce(orderChilder.getDishRequire());
                orderDishVo.setType(dish.getType());
                shopId = dish.getShopId();
                LambdaQueryWrapper<HgMallShop> lmShop=new LambdaQueryWrapper<>();
                lmShop.select(HgMallShop::getName);
                lmShop.eq(HgMallShop::getId,shopId);
                shopName = hgMallShopMapper.selectOne(lmShop).getName();
                //菜品总价
                BigDecimal dishPriceAll = dish.getPrice().multiply(new BigDecimal(orderChilder.getDishCount()));
                //在订单总价上累加菜品总价得到的结果就是订单总价
                orderPriceAll = orderPriceAll.add(dishPriceAll);
                //一个订单中有多个菜品
                dishList.add(orderDishVo);
            }
            //向订单中加入订单总价格
            orders.setPriceAll(orderPriceAll);
            orders.setShopId(shopId);
            orders.setShopName(shopName);
            //向订单中加入菜品
            orders.setOrderDishVo(dishList);
        }
        return hgMallOrders;
    }


    public LambdaQueryWrapper<HgMallDish> getlmHgMallDish(){
        LambdaQueryWrapper<HgMallDish> lmDish=new LambdaQueryWrapper<>();
        lmDish.select(
                HgMallDish::getId,
                HgMallDish::getName,
                HgMallDish::getIntroduce,
                HgMallDish::getPrice,
                HgMallDish::getType,
                HgMallDish::getStatus,
                HgMallDish::getShopId,
                HgMallDish::getDelFlag,
                HgMallDish::getSales,
                HgMallDish::getImg);
        return lmDish;
    }

    public LambdaQueryWrapper<HgMallOrders> getlmHgMallOrders(){
        LambdaQueryWrapper<HgMallOrders> lm = new LambdaQueryWrapper<>();
        lm.select(
                HgMallOrders::getId,
                HgMallOrders::getAppid,
                HgMallOrders::getShopId,
                HgMallOrders::getMealStatus,
                HgMallOrders::getStatus,
                HgMallOrders::getOddNum,
                HgMallOrders::getOrderNum,
                HgMallOrders::getDelFlag);
        lm.eq(HgMallOrders::getDelFlag,0);
        return lm;
    }

    public LambdaQueryWrapper<HgMallOrderChilder> getlmHgMallOrdersChilder(){
        LambdaQueryWrapper<HgMallOrderChilder> lmOrderChiler=new LambdaQueryWrapper<>();
        lmOrderChiler.select(
                HgMallOrderChilder::getId,
                HgMallOrderChilder::getDishId,
                HgMallOrderChilder::getOrdersId,
                HgMallOrderChilder::getDelFlag,
                HgMallOrderChilder::getDishRequire,
                HgMallOrderChilder::getDishCount
        );
        return lmOrderChiler;
    }






    public List<Integer> getdishIdByOrderId(String orderId){
        List<Integer> idList= new ArrayList<>();
        LambdaQueryWrapper<HgMallOrderChilder> lm=new LambdaQueryWrapper<>();
        lm.select(HgMallOrderChilder::getDishId);
        lm.eq(HgMallOrderChilder::getOrdersId,orderId);
        idList=  hgMallOrderChilderMapper.selectList(lm).stream().map((item)->{
                return  item.getDishId();
        }).collect(Collectors.toList());
        return idList;
    }
}
